//
//  MainLinesVC.m
//  TuYouAPP
//
//  Created by L on 14-2-18.
//
//

#import "MainLinesVC.h"
#import "MainLineCell.h"
#import "PublishVC.h"
#import "DynamicDetailVC.h"
#import <AVOSCloud/AVOSCloud.h>
#import "DataModel.h"
#import "MySelfInfoVC.h"
#import "LoginVC.h"
#import "DataModel.h"
#import "UIImageView+WebCache.h"
#import <AVOSCloud/AVOSCloud.h>
#import "LoginVC.h"
#import "Util.h"
#import <AudioToolbox/AudioToolbox.h>

#import <QuartzCore/QuartzCore.h>
@interface MainLinesVC ()
{
    UIImageView *postImage;
    
}

@end
MainLinesVC *sharevc;
@implementation MainLinesVC
{
    NSArray*    _linedataarr;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        sharevc = self;
    }
    return self;
}
-(void)loadView
{
    self.isBackBtn = YES;
    [super loadView];
    self.LeftBarTitle = @"我的";
    self.Title = @"选择路线";
    self.RightBarTitle = @"发布";
}
+(MainLinesVC *)shareVC
{
    if (sharevc) {
        return sharevc;
        
    }
    else
        return nil;
}
- (void)viewDidLoad
{
   // self.navBar.leftBtn
    self.mPageName = @"线路";
    [super viewDidLoad];
    
    
    

    // Do any additional setup after loading the view from its nib.
    [TYUtil updateUserPoint];
    self.badgeView = [[JSBadgeView alloc] initWithParentView:self.navBar.leftBtn alignment:JSBadgeViewAlignmentTopRight];
    
    [self initWithRefreshTableViewIos7:CGRectMake(0, 64, 320, DEVICE_Height-64) Ios6rect:CGRectMake(0, 44, 320, DEVICE_Height-64)];
    UIView *herader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    herader.backgroundColor = [UIColor clearColor];
    postImage = [[UIImageView alloc]initWithFrame:CGRectMake(6, 7, 308, 45)];
    UIButton *deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(280, 20, 40, 20)];
    [deleteBtn addTarget:self action:@selector(removeHeader:) forControlEvents:UIControlEventTouchUpInside];
   [ deleteBtn setBackgroundColor:[UIColor clearColor]];
  //  postImage.image = [UIImage imageNamed:@"post.png"];
    [herader addSubview:postImage];
    [herader addSubview:deleteBtn];
    [TYAd getTYAD:^(TYAd *oneAD, NSString *err) {
        NSURL *url = [NSURL URLWithString:oneAD.mimgURL];
        [postImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"post.png"]];
    }];
    self.tableview.tableFooterView = herader;
    self.tableview.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableview.backgroundColor = ColorRGB(239, 239, 239);
    [self.view addSubview:self.tableview];
    
    [SVProgressHUD showWithStatus:@"加载中"];
    [TYLine getAllLines:^(NSArray *all, NSString *err) {
        [SVProgressHUD dismiss];
        if( all )
        {
            _linedataarr = all;
            [self.tableview reloadData];
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:err];
        }
        
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifcomin:) name:@"pushmsg" object:nil];
    
    
    
}

-(void)notifcomin:(NSNotification*)it
{
   // [self updateBadge];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
  //  [self updateBadge];
      [[TYUser currentUser] getAllNotDealCount:^(NSInteger count, NSString *eror) {
//          if (count == 0) {
//              <#statements#>
//          }
      }];
}
-(void)removeHeader:(UIButton *)sender
{
    [UIView animateWithDuration:0.2 animations:^{
        self.tableview.tableFooterView = nil;
    }];
}
-(void)leftBtnTouched:(id)sender
{
    MySelfInfoVC *vc = [[MySelfInfoVC alloc]initWithNibName:@"MySelfInfoVC" bundle:nil];
    if ([TYUser isNeedLogin]) {
        LoginVC *logvc = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
        logvc.tagVC = vc;
        [self.navigationController pushViewController:logvc animated:YES];
        return;

    }
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)rightBtnTouched:(id)sender
{
    PublishVC *vc = [[PublishVC alloc]init];
    vc.comeFrom = 1;
    
    if ([TYUser isNeedLogin]) {
        LoginVC *login = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
//        [self presentViewController:login animated:YES completion:nil];
        login.tagVC = vc;
        [self.navigationController pushViewController:login animated:YES];
        return;
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if( _linedataarr == nil ) return 0;
    return _linedataarr.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CustomCellIdentifier = @"MainLineCell";
    
    BOOL isUsed = NO;
    
    MainLineCell *cell = (MainLineCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    
    if (!isUsed && cell == nil ) {
        UINib *nib = [UINib nibWithNibName:@"MainLineCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"MainLineCell"];
        isUsed = YES;
        
        cell = (MainLineCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    }
    
    
    TYLine* oneline = [_linedataarr objectAtIndex:indexPath.row];
    
 //   int l = [oneline.mTopUserStatus.mContext rangeOfString:@":"].location;
    
    if( oneline.mTopUserStatus.mContext == nil || oneline.mTopUserStatus.mContext.length == 0  )
    {
        cell.noticeView.hidden =YES;
    }
    else
    {
        NSMutableString *topStr = [[NSMutableString alloc]initWithFormat:@"@%@:",oneline.mTopUserStatus.mTaguser.mUserDisplayName];
        int l = oneline.mTopUserStatus.mTaguser.mUserDisplayName.length;
        [topStr appendString:oneline.mTopUserStatus.mContext];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:topStr];
        
        [str addAttribute:NSForegroundColorAttributeName value:ColorRGB(205, 136, 52) range:NSMakeRange(0,l+1)];
        
        cell.noticeLabel.attributedText = str;
        [cell updateUI:[str string] lineTitle:oneline.mLineName];
        cell.noticeView.hidden =NO;
    }
    cell.lineTitle.text = oneline.mLineName;

    NSString *tonglucount = [NSString stringWithFormat:@"%d",oneline.mSameWayCount];
       int la = tonglucount.length;
    NSString *tonglustr = [NSString stringWithFormat:@"同路%@人",tonglucount];
    
        NSMutableAttributedString *abc = [[NSMutableAttributedString alloc] initWithString:tonglustr];
        
        [abc addAttribute:NSForegroundColorAttributeName value:ColorRGB(205, 136, 52) range:NSMakeRange(2,la)];

    cell.tonglucoutLabel.attributedText = abc;
    [cell.bgImag setImageWithURL:[NSURL URLWithString:oneline.mBackImgURL]  placeholderImage:[UIImage imageNamed:@"1.png"]];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 148;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DynamicDetailVC *vc = [[DynamicDetailVC alloc]init];
 
    TYLine* l = [_linedataarr objectAtIndex:indexPath.row];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    if (l.mTopUserStatus.mContext.length!=0) {
        
        if ([[ud objectForKey:l.mOjid]isEqualToString:l.mTopUserStatus.objId]&&[[ud objectForKey:l.mTopUserStatus.objId]boolValue]) {
            
        
        
        
        
        
        
        
        }
        else
        {
            NSString *oldid = [ud objectForKey:l.mOjid];
            if (oldid) {
                [ud removeObjectForKey:oldid];
                
            }
            //[ud removeObjectForKey:@"nowTopObjID"];
            //    [ud setObject:l.mTopUserStatus.objId forKey:@"nowTopObjID"];
            [ud setObject:l.mTopUserStatus.objId forKey:l.mOjid];
            vc.topUserState = l.mTopUserStatus;
        }
        
        
    }
    vc.lineTitle = l.mLineName;
    vc.mTagLine = l;
    [self.navigationController pushViewController:vc animated:YES];
    



}
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [TYAd getTYAD:^(TYAd *oneAD, NSString *err) {
        NSURL *url = [NSURL URLWithString:oneAD.mimgURL];
        [postImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"post.png"]];
    }];

    [TYLine getAllLines:^(NSArray *all, NSString *err) {
        [self.slimeView endRefresh];
        if( all )
        {
            _linedataarr = all;
            [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
            [self.tableview reloadData];
            
        }
        else{
            [SVProgressHUD showErrorWithStatus:err];
        }

    }];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}








@end
